package gui;

import dto.LogDTO;
import dto.MedicoDTO;
import dto.PacienteDTO;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import static jr.Reporter.ComprobanteTurnoReport;
import logic.ComprobanteTurno;
import logic.Log;
import logic.Medico;
import logic.Paciente;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperPrintManager;
import net.sf.jasperreports.view.JasperViewer;
import util.InputHelper;

/**
 *
 * @author lucifer
 */
public class LogsPanel extends javax.swing.JPanel implements Slave {

  private Master master;

  public void SetMaster(Master master) {
    this.master = master;
  }

  public void SetModeActions() {
    ((JFrame) master).setTitle("Log de Turnos - Senzu");
  }

  private ArrayList<Integer> lIDs;
  private ArrayList<Integer> mIDs;
  private ArrayList<Integer> pIDs;
  public boolean ShowComprobantes;

  public LogsPanel(Master master) {
    SetMaster(master);

    initComponents();

    Busqueda();
  }

  public void Busqueda() {
    try {
      updateTabla(Log.All());
      setUpMedicosComboBox(medicosjComboBox);
      setUpPacientesComboBox(pacientesjComboBox);
    } catch (SQLException e) {
      System.out.printf("?l:database connection failed\n");
    }
  }

  private void setUpMedicosComboBox(JComboBox c) throws SQLException {
    ArrayList<MedicoDTO> dtos = Medico.All();
    String[] medicos = new String[dtos.size() + 1];
    mIDs = new ArrayList<>();
    medicos[0] = "Todos";
    mIDs.add(-1);
    for (int i = 1; i < medicos.length; i++) {
      medicos[i] = dtos.get(i - 1).getNombre() + " " + dtos.get(i - 1).getApellido();
      mIDs.add(dtos.get(i - 1).getId());
    }
    c.setModel(new DefaultComboBoxModel(medicos));
    c.setSelectedIndex(0);
  }

  private void setUpPacientesComboBox(JComboBox c) throws SQLException {
    ArrayList<PacienteDTO> dtos = Paciente.All();
    String[] pacientes = new String[dtos.size() + 1];
    pIDs = new ArrayList<>();
    pacientes[0] = "Todos";
    pIDs.add(-1);
    for (int i = 1; i < pacientes.length; i++) {
      pacientes[i] = dtos.get(i - 1).getNombre() + " " + dtos.get(i - 1).getApellido();
      pIDs.add(dtos.get(i - 1).getId());
    }
    c.setModel(new DefaultComboBoxModel(pacientes));
    c.setSelectedIndex(0);
  }

  private void updateTabla(ArrayList<LogDTO> l) {
    DefaultTableModel m = new DefaultTableModel();
    m.addColumn("Fecha");
    m.addColumn("Médico");
    m.addColumn("Paciente");
    m.addColumn("Estado Actual");
    m.addColumn("Asignado el");
    m.addColumn("Asignado por");

    lIDs = new ArrayList<>();
    for (int i = 0; i < l.size(); i++) {
      lIDs.add(l.get(i).getId());
      m.addRow(
        new Object[] {
          l.get(i).getFecha(),
          l.get(i).getMedico(),
          l.get(i).getPaciente(),
          l.get(i).getEstadoActual(),
          l.get(i).getAsignadoEl(),
          l.get(i).getAsignadoPor()
        }
      );
    }
    buscarjTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    buscarjTable.setModel(m);
  }

  private void printAgain(int idTurno) throws SQLException, JRException {

    ComprobanteTurno comprobante = new ComprobanteTurno(idTurno);
    JasperPrint jp = ComprobanteTurnoReport(comprobante.GenerarComprobante());

    if (ShowComprobantes) {
      JasperViewer viewer = new JasperViewer(jp, false);
      viewer.setTitle("Comprobante de Turno");
      viewer.setVisible(true);
      viewer.setFitWidthZoomRatio();
    } else {
      JasperPrintManager.printReport(jp, true);
    }

  }

  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    buscarjTable = new JTable() {
      public boolean isCellEditable(int i, int j) {
        return false;
      }
    };
    printjButton = new javax.swing.JButton();
    volverjButton = new javax.swing.JButton();
    medicosjComboBox = new javax.swing.JComboBox();
    pacientesjComboBox = new javax.swing.JComboBox();
    desdejDateChooser = new kalendar.calendar.JDateChooser();
    hastajDateChooser = new kalendar.calendar.JDateChooser();
    buscarjButton = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();

    buscarjTable.setModel(new javax.swing.table.DefaultTableModel(
      new Object [][] {

      },
      new String [] {
        "Fecha", "Médico", "Paciente", "Estado Actual", "Asignado el", "Asignado por"
      }
    ) {
      Class[] types = new Class [] {
        java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
      };
      boolean[] canEdit = new boolean [] {
        false, false, false, false, false, false
      };

      public Class getColumnClass(int columnIndex) {
        return types [columnIndex];
      }

      public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit [columnIndex];
      }
    });
    buscarjTable.getTableHeader().setReorderingAllowed(false);
    jScrollPane1.setViewportView(buscarjTable);

    printjButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/print.png"))); // NOI18N
    printjButton.setText("Reimprimir comprobante de turno");
    printjButton.setMaximumSize(new java.awt.Dimension(298, 27));
    printjButton.setMinimumSize(new java.awt.Dimension(298, 27));
    printjButton.setPreferredSize(new java.awt.Dimension(298, 27));
    printjButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        printjButtonActionPerformed(evt);
      }
    });

    volverjButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/go_back.png"))); // NOI18N
    volverjButton.setText("Volver a Asignación de Turnos");
    volverjButton.setMaximumSize(new java.awt.Dimension(298, 27));
    volverjButton.setMinimumSize(new java.awt.Dimension(298, 27));
    volverjButton.setPreferredSize(new java.awt.Dimension(298, 27));
    volverjButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        volverjButtonActionPerformed(evt);
      }
    });

    medicosjComboBox.setMaximumSize(new java.awt.Dimension(186, 27));
    medicosjComboBox.setMinimumSize(new java.awt.Dimension(186, 27));
    medicosjComboBox.setPreferredSize(new java.awt.Dimension(186, 27));

    pacientesjComboBox.setMaximumSize(new java.awt.Dimension(186, 27));
    pacientesjComboBox.setMinimumSize(new java.awt.Dimension(186, 27));
    pacientesjComboBox.setPreferredSize(new java.awt.Dimension(186, 27));

    desdejDateChooser.setDateFormatString("dd/MM/yyyy");

    hastajDateChooser.setDateFormatString("dd/MM/yyyy");

    buscarjButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/search.png"))); // NOI18N
    buscarjButton.setText("Buscar");
    buscarjButton.setMaximumSize(new java.awt.Dimension(176, 27));
    buscarjButton.setMinimumSize(new java.awt.Dimension(176, 27));
    buscarjButton.setPreferredSize(new java.awt.Dimension(176, 27));
    buscarjButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        buscarjButtonActionPerformed(evt);
      }
    });

    jLabel1.setText("Desde");

    jLabel2.setText("Hasta");

    jLabel3.setText("Médicos");

    jLabel4.setText("Pacientes");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(layout.createSequentialGroup()
            .addComponent(printjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(volverjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(desdejDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(jLabel1))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(hastajDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(jLabel2))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(medicosjComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(jLabel3))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel4)
                .addGap(0, 0, Short.MAX_VALUE))
              .addGroup(layout.createSequentialGroup()
                .addComponent(pacientesjComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buscarjButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
          .addComponent(jScrollPane1))
        .addGap(0, 0, 0))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
          .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(jLabel1)
              .addComponent(jLabel2)
              .addComponent(jLabel3)
              .addComponent(jLabel4))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(desdejDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(medicosjComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(pacientesjComboBox, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(buscarjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
          .addComponent(hastajDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 449, Short.MAX_VALUE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(printjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(volverjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
    );
  }// </editor-fold>//GEN-END:initComponents

  private void printjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_printjButtonActionPerformed
    if (buscarjTable.getSelectedRow() == -1) {
			JOptionPane.showMessageDialog(this, "No seleccionó ningún turno. Seleccione un turno, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return;
    }

    try {
      printAgain(lIDs.get(buscarjTable.getSelectedRow()));
    } catch (Exception e) {
      JOptionPane.showMessageDialog(
        this,
        "No es posible reimprimir el comprobante del turno.", "Error!",
        JOptionPane.ERROR_MESSAGE
      );
    }
  }//GEN-LAST:event_printjButtonActionPerformed

  private void volverjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_volverjButtonActionPerformed
    master.ShowSlave(master.TurnoGrepPanel());
  }//GEN-LAST:event_volverjButtonActionPerformed

  private void buscarjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscarjButtonActionPerformed
    Date d = desdejDateChooser.getDate();
    LocalDate desde = d != null ? InputHelper.FromOldDateToNew(d).toLocalDate() : null;
    Date h = hastajDateChooser.getDate();
    LocalDate hasta = h != null ? InputHelper.FromOldDateToNew(h).toLocalDate() : null;
    try {
      updateTabla(Log.Search(desde, hasta, mIDs.get(medicosjComboBox.getSelectedIndex()), pIDs.get(pacientesjComboBox.getSelectedIndex())));
    } catch (Exception e) {
    }
  }//GEN-LAST:event_buscarjButtonActionPerformed

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton buscarjButton;
  private javax.swing.JTable buscarjTable;
  private kalendar.calendar.JDateChooser desdejDateChooser;
  private kalendar.calendar.JDateChooser hastajDateChooser;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JComboBox medicosjComboBox;
  private javax.swing.JComboBox pacientesjComboBox;
  private javax.swing.JButton printjButton;
  private javax.swing.JButton volverjButton;
  // End of variables declaration//GEN-END:variables
}
